package medusa

import (
    "fmt"
    "net"
)

//////////////////////////////////////////////////////////////////////////
//Acceptor
//////////////////////////////////////////////////////////////////////////

type Acceptor interface {
    GetName() string
    startup(fd *net.TCPConn)
    shutdown()
    Close()
    SendPacket(pack *Packet)

    GetFD() *net.TCPConn
    GetUUID() int
    GetUUID32() int32
    GetListener() Listener
    GetLocalAddr() net.Addr
    GetRemoteAddr() net.Addr
}

//////////////////////////////////////////////////////////////////////////
//TcpAcceptor
//////////////////////////////////////////////////////////////////////////
type TcpAcceptor struct {
    Socket

    name string
    listen    Listener
    conn_lose func()
}

func NewAcceptor(listen Listener, uuid int,
    ecb_idle func(),
    ecb_pre_sent func(pack *Packet),
    ecb_conn_lose func(),
    ecb_packet_received func(pack *Packet)) *TcpAcceptor {

    acc := new(TcpAcceptor)
    acc.Constructor(listen, uuid, ecb_idle, ecb_pre_sent, ecb_conn_lose, ecb_packet_received)

    return acc
}

func (self *TcpAcceptor) Constructor(listen Listener, uuid int,
    ecb_idle func(),
    ecb_pre_sent func(pack *Packet),
    ecb_conn_lose func(),
    ecb_packet_received func(pack *Packet)) {

    self.listen = listen
    self.name = fmt.Sprintf("%v-Acceptor", self.listen.GetName())

    self.conn_lose = func() {
        if ecb_conn_lose != nil {
            ecb_conn_lose()
        }
        go func() {
            self.Wait()
            self.listen.CallMethod("listen-conn-lose", self)
        }()
    }

    self.Socket.constructor(self.name, uuid,
        self.listen.get_max_idle(),
        self.listen.get_rcvbuf_size(),
        self.listen.get_sndbuf_size(),
        self.listen.get_sndchan_num(),
        self.listen.get_log(),
        ecb_idle, ecb_pre_sent, self.conn_lose, ecb_packet_received)
}

func (self *TcpAcceptor) GetName() string {
    return self.name
}

func (self *TcpAcceptor) GetListener() Listener {
    return self.listen
}
